import axios from "axios";

const instance = axios.create({
    baseURL: "http://smartdp.com",
    timeout: 5000
});

// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// instance.defaults.headers.post['Accept'] = 'application/json';

const defaultOpt = { login: true };

function baseRequest(options) {
    const headers = options.headers || {};
    options.headers = headers;
    return instance(options).then(res => {
        const data = res.data || {};

        if (res.status !== 200)
            return { msg: "请求失败", res, data };

        return { msg: res.data.msg, res, data };
    });
}

/**
 * http 请求基础类
 * 参考文档 https://www.kancloud.cn/yunye/axios/234845
 *
 */
const request = ["post", "put", "patch"].reduce((request, method) => {
    /**
     *
     * @param url string 接口地址
     * @param data object get参数
     * @param options object axios 配置项
     * @returns {AxiosPromise}
     */
    request[method] = (url, data = {}, options = {}) => {
        return baseRequest(
            Object.assign({ url, data, method }, defaultOpt, options)
        );
    };
    return request;
}, {});

["get", "delete", "head"].forEach(method => {
    /**
     *
     * @param url string 接口地址
     * @param params object get参数
     * @param options object axios 配置项
     * @returns {AxiosPromise}
     */
    request[method] = (url, params = {}, options = {}) => {
        return baseRequest(
            Object.assign({ url, params, method }, defaultOpt, options)
        );
    };
});

export default request;
